<?php
/**
 * 视频
 * Author: 毛康燕
 * Date: 2021/6/17
 */

namespace app\backend\controller\v1;

use app\backend\validate\VideoValidate;
use app\BaseController;
use app\common\model\Video as VideoModel;
use think\exception\ValidateException;
use think\facade\Filesystem;

class Video extends BaseController
{
    //显示
    public function index()
    {
        $model = new VideoModel();
        $page = input('page/d', 1);
        $ban = $model
            ->page($page, 5)
            ->select();
        $count = $model
            ->count();
        $maxpage = ceil($count / 5);
        return sucessMsg(200, '获取成功！', ['ban' => $ban, 'maxpage' => $maxpage]);
    }

    //添加
    public function create()
    {
        $user = new VideoModel();
        $data = input();
        $data['video'] = delYuming($data['video']);
        try {
            validate(VideoValidate::class)->scene('create')->check($data);
            if ($user->save($data)) {
                return sucessMsg(200, '创建成功！', $user->id);
            }
            return errMsg(500, '创建失败！');
        } catch (ValidateException $e) {
            return errMsg(400, $e->getError());
        }
    }

    //修改
    public function update()
    {
        $id = input('id/d');
        if (empty($id)) {
            return errMsg(400, '请选择id');
        }
        $user = VideoModel::find($id);
        $data = input();
        $data['video'] = delYuming($data['video']);
        try {
            validate(VideoValidate::class)->scene('update')->check($data);
            if (VideoModel::update($data, ['id' => $id])) {
                return sucessMsg(200, '修改成功！', $user->id);
            }
            return errMsg(500, '修改失败！');
        } catch (ValidateException $e) {
            return errMsg(400, $e->getError());
        }
    }

    //删除
    public function delete()
    {
        $data = input();
        $model = VideoModel::where('id', $data['id'])->delete();
        if ($model) {
            return sucessMsg(200, '删除成功！');
        } else {
            return errMsg(500, '删除失败！');
        }
    }

    //视频上传
    public function uploads_video()
    {
        if (!request()->file()) {
            return errMsg(500, '未上传视频！');
        }
        $file = request()->file('file');
        if (empty($file)) {
            return errMsg(500, '未上传视频！');
        }
        $temp = explode(".", $_FILES["file"]["name"]);
        $extension = end($temp);

        if (!in_array($extension, array("mp4"))) {
            return errMsg(500, '上传视频不合法！');
        }
        $saveName = Filesystem::disk('public')->putFile('uploads', $file);
        $phonto_name = env('DATABASE.YUMING') . str_replace('\\', '/', $saveName);
        return sucessMsg(200, '上传成功！', $phonto_name);
    }
}